import React, { useEffect, useRef, useCallback } from 'react';
import { notification } from 'antd';
import { connectWebSocket, disconnectWebSocket } from '@/utils/webSocket.js';

export default function AuditNotification() {
  const connectionRef = useRef(false);
  const reconnectTimer = useRef(null);

  const handleMessage = useCallback((message) => {
    notification.success({
      message: '📢 新员工待审核',
      description: (
        <div>
          <p>姓名：{message.name}</p>
          <p>提交时间：{new Date(message.timestamp).toLocaleString()}</p>
          <a href={`/audit/${message.id}`}>立即处理</a>
        </div>
      ),
      placement: 'bottomRight',
      duration: 8
    });
  }, []);

  const setupWebSocket = useCallback(() => {
    if (!connectionRef.current) {
      connectionRef.current = true;
      connectWebSocket((message) => {
        handleMessage(message);
        connectionRef.current = true;
      });
    }
  }, [handleMessage]);

  useEffect(() => {
    setupWebSocket();

    const checkConnection = () => {
      if (!connectionRef.current) {
        console.log('检测到连接断开，尝试重新连接...');
        setupWebSocket();
      }
    };

    reconnectTimer.current = setInterval(checkConnection, 15000);

    return () => {
      disconnectWebSocket();
      clearInterval(reconnectTimer.current);
      connectionRef.current = false;
    };
  }, [setupWebSocket]);

  return null;
}